package com.yuezhu.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yuezhu.Model.ProjectModel;
import com.yuezhu.R;
import com.yuezhu.adapter.MyProjectLeftAdapter;
import com.yuezhu.been.DataChangedEvent;
import com.yuezhu.been.UserMsg;
import com.yuezhu.citylist.CityModel;
import com.yuezhu.constante.BusAction;
import com.yuezhu.fragment.DiantiNumFragment;
import com.yuezhu.fragment.MyProjectContentFragment;
import com.yuezhu.fragment.MyrojectFragment;
import com.yuezhu.fragment.PartitionnformationFragment;
import com.yuezhu.global.BaseActivity;
import com.yuezhu.global.ParallaxSwipeBackActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MyprojectActivity extends BaseActivity implements AdapterView.OnItemClickListener, DrawerLayout.DrawerListener {
    public static ProjectModel currentProjectModel = null;
    public static ArrayList<CityModel> mCityModels;

    public static String getCityNameById(int id) {
        if (mCityModels == null) {
            return "";
        }
        for (CityModel model : mCityModels) {
            if (model.getId() == id) {
                return model.getName();
            }
        }
        return "";
    }

    @InjectView(R.id.main_content)
    FrameLayout mContent;
    @InjectView(R.id.main_left)
    ListView mlistview;
    @InjectView(R.id.main_drawerlayout)
    DrawerLayout mDrawerlayout;
    @InjectView(R.id.iv_menu)
    ImageView ivMenu;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_quite)
    ImageView ivQuite;
    @InjectView(R.id.tv_version)
    TextView tvVersion;
    private MyProjectLeftAdapter mLeftAdapter;
    private FragmentManager fragmentManager;
    private MyProjectContentFragment mContentFragment;
    private MyrojectFragment myrojectFragment;
    private DiantiNumFragment diantiNumFragment;
    private PartitionnformationFragment partitionnformationFragment;

    private boolean isOpen = false;//菜单是否打开

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myproject);
        ButterKnife.inject(this);
        initView();
        initFragment();
        initData();
        setListeners();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ivMenu.setImageResource(R.drawable.menu);
        tvTitle.setText("我的项目");
        ivQuite.setVisibility(View.GONE);
        tvVersion.setVisibility(View.VISIBLE);
        if (UserMsg.getInstance().getLevel() == 0) {
            tvVersion.setText("1.0基本版");
        } else {
            tvVersion.setText("1.0高级版");
        }
    }

    private void initData() {
        mLeftAdapter = new MyProjectLeftAdapter(this);
        mlistview.setAdapter(mLeftAdapter);
    }

    private void initFragment() {
        fragmentManager = getFragmentManager();
        mContentFragment = (MyProjectContentFragment) fragmentManager.findFragmentById(R.id.fragment_content);
        myrojectFragment = (MyrojectFragment) fragmentManager.findFragmentById(R.id.fragment_base_message);
        partitionnformationFragment = (PartitionnformationFragment) fragmentManager.findFragmentById(R.id.fragment_base_part1);
        diantiNumFragment = (DiantiNumFragment) fragmentManager.findFragmentById(R.id.fragment_base_part2);
        fragmentManager.beginTransaction().show(mContentFragment).hide(diantiNumFragment).hide(myrojectFragment).hide(partitionnformationFragment).commit();
    }

    @Subscribe
    public void onEventMainThread(BusAction.myMess event) {
        fragmentManager.beginTransaction().hide(diantiNumFragment).hide(mContentFragment).hide(partitionnformationFragment).show(myrojectFragment).commit();
        myrojectFragment.show();
        tvTitle.setText("建筑基本信息");
    }

    @Subscribe
    public void onEventMainThread(BusAction.mymessBack event) {
        fragmentManager.beginTransaction().hide(diantiNumFragment).show(mContentFragment).hide(partitionnformationFragment).hide(myrojectFragment).commit();
        tvTitle.setText("我的项目");
        mContentFragment.show();
    }

    @Subscribe
    public void onEventMainThread(BusAction.mymessPart1 event) {
        tvTitle.setText("建筑分区信息");
        fragmentManager.beginTransaction().hide(diantiNumFragment).hide(mContentFragment).show(partitionnformationFragment).hide(myrojectFragment).commit();
        partitionnformationFragment.show();
    }

    @Subscribe
    public void onEventMainThread(BusAction.mymessDianti event) {
        tvTitle.setText("建议的电梯数量");
        fragmentManager.beginTransaction().show(diantiNumFragment).hide(mContentFragment).hide(partitionnformationFragment).hide(myrojectFragment).commit();
        diantiNumFragment.show();
    }

    @Subscribe
    public void onEventMainThread(BusAction.quitLogin event) {
        finish();
    }

    @Subscribe
    public void onEventMainThread(BusAction.quitApp event) {
        finish();
    }

    // 订阅事件DataChangedEvent
    public void setCardEvent(DataChangedEvent event) {
        switch (event.getAction()) {
            case BusAction.MYMESS:
                fragmentManager.beginTransaction().hide(diantiNumFragment).hide(mContentFragment).hide(partitionnformationFragment).show(myrojectFragment).commit();
                myrojectFragment.show();
                tvTitle.setText("建筑基本信息");
                break;
            case BusAction.MYMESS_BACK:
                fragmentManager.beginTransaction().hide(diantiNumFragment).show(mContentFragment).hide(partitionnformationFragment).hide(myrojectFragment).commit();
                tvTitle.setText("我的项目");
                mContentFragment.show();
                break;
            case BusAction.MYMESS_PART1:
                tvTitle.setText("建筑分区信息");
                fragmentManager.beginTransaction().hide(diantiNumFragment).hide(mContentFragment).show(partitionnformationFragment).hide(myrojectFragment).commit();
                partitionnformationFragment.show();
                break;
            case BusAction.MYMESS_DIANTI:
                tvTitle.setText("建议的电梯数量");
                fragmentManager.beginTransaction().show(diantiNumFragment).hide(mContentFragment).hide(partitionnformationFragment).hide(myrojectFragment).commit();
                break;
            case BusAction.QUIT_LOGIN:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mlistview.setOnItemClickListener(this);
        ivMenu.setOnClickListener(this);
        mDrawerlayout.setDrawerListener(this);
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.iv_menu:
                if (isOpen) {
                    mDrawerlayout.closeDrawers();
                } else {
                    mDrawerlayout.openDrawer(Gravity.LEFT);
                }
                break;
        }
    }

    private int Index = 0;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position != 0) {
            mDrawerlayout.closeDrawers();
            Index = position;
        }

    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }

    @Override
    public void onDrawerOpened(View drawerView) {
        isOpen = true;
    }

    @Override
    public void onDrawerClosed(View drawerView) {
        isOpen = false;
        if (Index != 0) {
            switch (Index) {
                case 1:
//                    screenshots(MyprojectActivity.this, false);
//                    startParallaxSwipeBackActivty(MyprojectActivity.this,
//                            new Intent(MyprojectActivity.this, AboutActivity.class));
                    openUrl("http://www.zcloud-online.com/AppService/AppInfo?appId=2016001");
                    break;
                case 2:
//                    screenshots(MyprojectActivity.this, false);
//                    startParallaxSwipeBackActivty(MyprojectActivity.this,
//                            new Intent(MyprojectActivity.this, MoreAppActivity.class));
                    openUrl("http://www.zcloud-online.com/AppService/AppsList?typeId=0");
                    break;
                case 3:
                    screenshots(MyprojectActivity.this, false);
                    startParallaxSwipeBackActivty(MyprojectActivity.this,
                            new Intent(MyprojectActivity.this, AccountInfoActivity.class));
                    break;
                case 4:
                    finish();
                    System.exit(0);
                    break;
            }
            Index = 0;
        }
    }

    private void openUrl(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    private long exitTime = 0;

    //退出程序提示
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出电梯速运助手",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return false;
    }

    public void screenshots(Activity activity, boolean isFullScreen) {
        try {
            // View是你需要截图的View
            View decorView = activity.getWindow().getDecorView();
            decorView.setDrawingCacheEnabled(true);
            decorView.buildDrawingCache();
            Bitmap b1 = decorView.getDrawingCache();
            // 获取状态栏高度 /
            Rect frame = new Rect();
            activity.getWindow().getDecorView()
                    .getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            // 获取屏幕长和高 Get screen width and height
            int width = activity.getWindowManager().getDefaultDisplay()
                    .getWidth();
            int height = activity.getWindowManager().getDefaultDisplay()
                    .getHeight();
            // 去掉标题栏 Remove the statusBar Height
            Bitmap bitmap;
            if (isFullScreen) {
                bitmap = Bitmap.createBitmap(b1, 0, 0, width, height);
            } else {
                bitmap = Bitmap.createBitmap(b1, 0, statusBarHeight, width,
                        height - statusBarHeight);
            }
            decorView.destroyDrawingCache();
            FileOutputStream out = new FileOutputStream(new File(getCacheDir(), ParallaxSwipeBackActivity.WINDOWBITMAP));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
